from django.core.paginator import Paginator
from django.db.models import Q
from app01.Baseview import BasedAPIView
from app01.models import NetDevice


class NetDevice_Api(BasedAPIView):
    def get_page_all(self, request):
        pageIndex = int(request.GET.get('pageIndex', 1))
        pageSize = int(request.GET.get('pageSize', 10))
        device_name = request.GET.get('name', None)
        query = Q()
        if device_name:
            query = query & Q(name__icontains=device_name)

        data = NetDevice.objects.filter(query).order_by('-id')
        page = Paginator(data, pageSize)
        resl = []
        for item in list(page.page(pageIndex)):
            data_dic = {
                'id': item.id,
                'device_name': item.name,
                'device_type': item.device_type,
                'ipaddress': item.ipaddress,
                'status': item.status,
                'community': item.community,
            }
            resl.append(data_dic)
        return super().success(data={
            'pageIndex': pageIndex,
            'pageSize': pageSize,
            'total': page.count,
            'data': resl
        }
        )
